﻿
namespace NetTao.Builder
{
    public class OpfBuilder : BuilderBase
    {
        private readonly OpfInfo _opfInfo=new OpfInfo();

        public void AddMetadata(Model.ArticleInfo article)
        {
            _opfInfo.Metadata = string.Format("<metadata><dc-metadata>" +
                                              "<dc:Title>{0}</dc:Title><dc:Creator>{1}</dc:Creator><dc:Subject></dc:Subject>" +
                                              "<dc:Description>{2}</dc:Description><dc:Publisher>QR</dc:Publisher><dc:Contributorid>{3}</dc:Contributorid>" +
                                              "<dc:Sortid>{4}</dc:Sortid><dc:Typeid>{5}</dc:Typeid><dc:Articletype>{6}</dc:Articletype>" +
                                              "<dc:Permission>{7}</dc:Permission><dc:Firstflag>{8}</dc:Firstflag><dc:Fullflag>{9}</dc:Fullflag>" +
                                              "<dc:Imgflag>{10}</dc:Imgflag><dc:Power>{11}</dc:Power><dc:Display>{12}</dc:Display>" +
                                              "<dc:Date>{13}</dc:Date><dc:Type>Text</dc:Type><dc:Format>text</dc:Format>" +
                                              "<dc:Language>ZH</dc:Language>" +
                                              "</dc-metadata></metadata>",
                                              article.articlename, article.author,
                                              article.intro, article.authorid,
                                              article.sortid, article.typeid, article.articletype,
                                              article.permission, article.firstflag, article.fullflag,
                                              article.imgflag, article.power, article.display, article.lastupdate);
        }

        public void AddMainfestAndSpine(Model.ChapterInfo chapter)
        {
            _opfInfo.Mainfest +=
                string.Format("<item id=\"{0}\" href=\"{1}.txt\" media-type=\"text/html\" content-type=\"chapter\" />",
                              chapter.articlename, chapter.articleid);
            _opfInfo.Spine += string.Format("<itemref idref=\"{0}\" />", chapter.chaptername);
        }

        public bool ConfirmOptFile(string filePath,int articleid)
        {
            string path = string.Format("{0}/files/article/txt/{1}/{2}", filePath, articleid/1000, articleid);
            if(!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            path += "/index.opf";
            string content =
                string.Format(
                    "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><package unique-identifier=\"http:///-2\">{0}{1}{2}</package>",
                    _opfInfo.Metadata, _opfInfo.Mainfest, _opfInfo.Spine);
            if(System.IO.File.Exists(path))
            {System.IO.File.Delete(path);}
            return Utils.XFile.WriteFile(path, content);
        }
    }
}
